<template>
  <div class="unit">
    <el-header>
      <el-select v-model="querryInfo.homestatus" clearable @clear="getUnit()" placeholder="入住状态" style="width: 200px;">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-input v-model="querryInfo.unitname" placeholder="单元名称" clearable @clear="getUnit()"
        style="width: 200px;"></el-input>
      <el-input v-model="querryInfo.buildnum" placeholder="幢号" clearable @clear="getUnit()"
        style="width: 200px;"></el-input>
      <el-input v-model="querryInfo.homenum" placeholder="房号" clearable @clear="getUnit()"
        style="width: 200px;"></el-input>
      <el-input v-model="querryInfo.homename" placeholder="住客姓名" clearable @clear="getUnit()"
        style="width: 200px;"></el-input>
      <el-button type="primary" @click="getUnit()" icon="el-icon-search">查询</el-button>
      <el-button type="success" @click="exportSelect()" icon="el-icon-upload2">批量导出</el-button>
      <el-button type="danger" @click="deleteNumber()" icon="el-icon-delete">批量删除</el-button>
    </el-header>

    <el-table ref='multipleTable' :data="unitList" tooltip-effect="dark" style="width: 100%; max-width: 100%;"
      v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center">
      </el-table-column>
      <el-table-column label="序号" align="center">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="单元名称" align="center">
        <template slot-scope="scope">{{ scope.row.unitname }}</template>
      </el-table-column>
      <el-table-column label="幢号" align="center">
        <template slot-scope="scope">{{ scope.row.buildnum != null ? scope.row.buildnum : '暂无' }}</template>
      </el-table-column>
      <el-table-column label="楼层号" align="center">
        <template slot-scope="scope">{{ scope.row.storeynum != null ? scope.row.storeynum : '暂无' }}</template>
      </el-table-column>
      <el-table-column label="房号" align="center">
        <template slot-scope="scope">{{ scope.row.homenum != null ? scope.row.homenum : '暂无' }}</template>
      </el-table-column>
      <el-table-column label="住客姓名" align="center">
        <template slot-scope="scope">{{ scope.row.homename != null ? scope.row.homename : '暂无' }}</template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">{{ getStatusLabel(scope.row.homestatus) }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="" style="color: #62a8ea;"
            @click="numberDetail(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteNumber(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination style="text-align: right;" :page="querryInfo.currPage" :componentTotal="unitTotal" @changeRows="setRows"
      @changePage="setPage">
    </pagination>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { excelExportUseJson, excelImport } from '../../assets/js/xlsx'
export default {
  data() {
    return {
      querryInfo: {
        homestatus: '',
        unitname: '',
        buildnum: '',
        homenum: '',
        homename: '',
        currPage: 0,
        pageNum: 10,
        token: sessionStorage.token,
      },
      unitForm: {
        unitstatus: '',
      },
      id: '',
      loading: false,
      unitList: [],
      multipleSelection: [],
      unitTotal: 0,
      statusOptions: [
        { value: '1', label: '已入住' },
        { value: '2', label: '未入住' },
      ],
      listHeader: {
        unitname: "单元名称",
        buildnum: "幢号",
        storeynum: "楼层号",
        homenum: "房号",
        homename: "住客姓名",
        homestatus: "状态",
      }
    };
  },
  computed: {
    getStatusLabel() {
      return (homestatus) => {
        const status = this.statusOptions.find(option => option.value == homestatus);
        return status ? status.label : '未入住';
      }
    }
  },
  components: {
    Pagination
  },
  mounted() {
    this.getUnit();
  },
  methods: {
    exportSelect() {
      // 导出复选框被勾选的数据
      const selectedData = this.multipleSelection;
      if (selectedData.length === 0) {
        this.$message.warning('请选择要导出的数据');
        return;
      }
      excelExportUseJson(selectedData, this.listHeader, "用户信息表");
    },

    importExcel(file) {
      console.log(file);
      excelImport(file.raw, 'json').then(res => {
        if (!res || !Array.isArray(res)) {
          this.$message.error('导入的数据格式不正确');
          return;
        }

        res = res.map(item => {
          let newUserFrom = {};
          for (let [headerKey, headerVal] of Object.entries(this.listHeader)) {
            newUserFrom[headerKey] = item[headerVal];
          }
          newUserFrom.passWord = 123456 // 使用安全的方式生成密码
          return newUserFrom;
        });

        console.log(res);
        this.handleImportedData(res); // 处理导入的数据
      }).catch(error => {
        this.$message.error('导入失败: ' + error.message);
      });
    },
    timeFormat() {
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let date = time.getDate();
      let hours = time.getHours();
      let minutes = time.getMinutes();
      let seconds = time.getSeconds();
      return year + '-' + this.addZero(month) + '-' + this.addZero(date) + ' ' + this.addZero(hours) + ':' + this.addZero(minutes) + ':' + this.addZero(seconds);
    },
    addZero(num) {
      return num < 10 ? '0' + num : num
    },

    // 分页器
    setRows(val) {
      this.querryInfo.pageNum = val;
      this.getUnit();
    },
    setPage(val) {
      this.querryInfo.currPage = val - 1;
      this.getUnit();
    },
    formatDateTime(createtime) {
      if (!createtime) return '';
      const date = new Date(createtime);
      const year = date.getFullYear().toString().slice(-2); // 获取年份的后两位
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
      const day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
      const hours = String(date.getHours()).padStart(2, '0'); // 获取小时并补零
      const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补零
      const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒并补零
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // async getUserByToken() {
    //   const { data: res } = await this.axios.get("/user/getUserByToken", {
    //     params: {
    //       token: sessionStorage.token
    //     }
    //   })
    //   console.log(res);
    // },
    async getUnit() {
      this.loading = true;
      const { data: res } = await this.axios.get("/house/searchnumList", {
        params: this.querryInfo,

      });
      // console.log(res);
      this.unitList = res.data
      this.unitTotal = res.total;
      console.log(this.unitList);
      this.loading = false;
    },
    // clickUnit() {
    //   setTimeout(() => {
    //     this.getUnit();
    //   }, 1000);
    // },
    async add() {
      this.$router.push({ name: 'Add', query: { type: 'ADD' } })
    },
    async unitDetail(index, row) {
      this.id = row.id;
      this.$router.push({ name: 'Add', query: { type: 'DETAIL', detailId: this.id } })
    },
    async numberDetail(index, row) {
      this.id = row.id;
      this.$router.push({ name: 'NumAdd', query: { type: 'DETAIL', editId: this.id } })
    },
    reset() {
      this.querryInfo.communityname = ''
      this.querryInfo.unitname = ''
      this.querryInfo.createDt = ''
      this.querryInfo.value = ''
      this.getUnit();
    },
    async deleteNumber(index, row) {
      let ids = [];
      if (row) {
        ids = [row.id];
      } else {
        ids = this.multipleSelection.map(item => item.id);
      }

      if (ids.length === 0) {
        this.$message.warning('请选择要删除的任务');
        return;
      }

      this.$confirm('确认删除选中的任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.axios.get("/house/delnumList?", { params: { ids, token: sessionStorage.token } });
          console.log(res);
          this.$message.success('删除成功');
          this.getUnit();
        } catch (error) {
          this.$message.error('删除任务失败: ' + error.message);
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleSelectionChange(val) {
      console.log(val)
      console.log(val.map(item => item.id))
      this.multipleSelection = val
      this.disabled = false
    }
  }
}
</script>

<style scoped lang="scss">
.unit {
  margin: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow-x: auto;

  .el-header {
    background-color: #fff;
    margin: 10px;
    line-height: 60px;


    .el-input,
    .el-select {
      margin: 5px 10px;
    }
  }
}
</style>
